#!/usr/bin/python
"""This will generate the n sequences each having motif of length l with d planted instances."""

import random
import sys

if len(sys.argv) < 5:
    print "arg 1: t(number of sequences), arg 2: n(length of each seq), arg 3: l(motif length), arg 4: d, arg 5: file-to-put-data[optional]"
    sys.exit(1)

bases = ['a', 'c', 'g', 't']

t = (int)(sys.argv[1])
n = (int)(sys.argv[2])
l = (int)(sys.argv[3])
d = (int)(sys.argv[4])

if len(sys.argv) == 6:
    filename = sys.argv[5]
    file = open(filename, 'w')

motif = ""

for tmp in xrange(l):
    motif += random.choice(bases)
# now we have our motif

if len(sys.argv) == 6:
    file.write(motif+"\n")
    file.write(sys.argv[1] + " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4] + "\n\n")
    
# generate t random sequences
seqs = []
seq = ""
for tmp in xrange(t):
    for tmp2 in xrange(n):
        seq += random.choice(bases)
    seqs.append(seq)
    seq = ""
# now we have our t sequences

for tmp in xrange(t):
    seq = seqs[tmp]
    pos = random.sample(xrange(l), d)
    motif_mod = []
    for m in motif:
        motif_mod.append(m)
        
    #print motif

    for i in pos:
        bases_mod = []
        for b in bases:
            if b != motif[i]:
                bases_mod.append(b)
        motif_mod[i] = random.choice(bases_mod)
        
    #print motif_mod
        
    insert_pos = random.choice(xrange(n-l+1))
    temp = ''
    for m in motif_mod:
        temp += m
    if len(sys.argv) == 6:
        file.write((str)(insert_pos) + " " + temp + "\n")
    
    seq1 = []
    
    for x in seq:
        seq1.append(x)
    
    for i in xrange(insert_pos, insert_pos+l):
        seq1[i] = motif_mod[i-insert_pos]
        
    seq = ""
    
    for x in seq1:
        seq += x
        
    seqs[tmp] = seq


for i in xrange(len(seqs)):
    #print ">seq", i
    print seqs[i]
        
        
        